package com.ibm.interfaces;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.message.MessageFields;
import com.ibm.cps.message.ParsedDataMessage;
import com.ibm.cps.newmessage.MetadataInputSchema;
import com.ibm.util.ErrorCode;
import com.ibm.util.JSONUtility;
import com.ibm.util.exception.CPSException;

public abstract class AbstractMessagePublisher {

	private String name;
	protected String tenantid;
	private String processorMetadta;
	private String type;

	public AbstractMessagePublisher(String metadata) throws CPSException {
		MetadataInputSchema schema = getInputSchema();
		if (schema == null) {
			throw new CPSException(ErrorCode.INTERNAL_ERROR_CODE, "No publisher metadata schema is defined.");
		}
		ObjectNode node = JSONUtility.fromObjectString(metadata);
		schema.validateInput(node);
		JSONUtility.checkNotNull(node, MessageFields.NAME);
		this.name = JSONUtility.GetString(MessageFields.NAME, node);
		if (!(name.startsWith("_") || name.charAt(0) >= 'a' && name.charAt(0) <= 'z'
				|| name.charAt(0) >= 'A' && name.charAt(0) <= 'Z')) {
			throw new CPSException(ErrorCode.INVALID_INPUT_ERROR,
					"Invalid publihser name " + name + ", it should start with [_|a-z|A-Z]");
		}
		JSONUtility.checkNotNull(node, MessageFields.TENANTID);
		this.tenantid = JSONUtility.GetString(MessageFields.TENANTID, node);
		JSONUtility.checkNotNull(node, MessageFields.TYPE);
		this.type = JSONUtility.GetString(MessageFields.TYPE, node);
		this.processorMetadta = metadata;
	}

	public String getName() {
		return name;
	}

	public String getTenantid() {
		return tenantid;
	}

	public String getProcessorMetadta() {
		return processorMetadta;
	}

	abstract public void publishMessage(ParsedDataMessage message, IMessageParser schema, boolean isBuffer) throws CPSException;

	abstract public MetadataInputSchema getInputSchema();

	abstract public void close();
}
